package com.tian.core.interceptor;


import com.tian.core.beans.ResultBean;
import com.tian.core.lang.Constant;
import com.tian.core.token.TokenManage;
import com.tian.core.utils.ShiroFilterUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Wenqiang Yang
 * @date 2018/01/16
 */
public class TokenInterceptor extends HandlerInterceptorAdapter {
    @Autowired
    private TokenManage tokenManage;

    /**
     * 该方法将在Controller处理之前进行调用
     * @param httpServletRequest
     * @param httpServletResponse
     * @param o
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        // 获取http header中的token
        String token = httpServletRequest.getHeader("token");
        ResultBean<?> result = new ResultBean<>();
        // 校验token有效性
        result = (ResultBean<?>) tokenManage.verify(token, result);
        if (result.getRespCode() != 0) {
            return true;
        }else{
            Map<String,Object> params = new HashMap<>();
            params.put(Constant.RESP_CODE,result.getRespCode());
            params.put(Constant.RESP_MSG,result.getRespMsg());
            params.put(Constant.DATA,null);
            // 对请求做出响应
            ShiroFilterUtils.out(httpServletResponse,params);
            return false;
        }
    }
}
